
const fs = require('fs');

function createDomMonitor_IsExist(monitorName, dom, execBody, interval) {
    return `const ${monitorName} = setInterval(() => {
        console.log('123');
        if (!(${dom} === null || ${dom}.length === 0)) {
            ${execBody};
            clearInterval(${monitorName});
        }
    }, ${interval});`
}

//将文件读取为数据流
function readFileAsStream(filePath) {
    const stream = fs.createReadStream(filePath);

    stream.on('end', function () {
        console.log('End of file');
    });

    stream.on('error', function (err) {
        console.log(`Error: ${err}`);
    });
}

//将文件读取为数组
function readFile(filePath, isSync) {
    if (isSync) {
        fs.readFileSync(filePath, (err, data) => {
            if (err) {
                console.error(err);
                return null;
            } else {
                console.log(data);
                return data;
            }
        });
    }
    fs.readFile(filePath, (err, data) => {
        if (err) {
            console.error(err);
            return null;
        } else {
            console.log(data);
            return data;
        }
    });
}

//动态添加脚本文件至网页
/**
 * 
 * @param {*} webContents 
 * @param {*} scriptPath 脚本文件要注意`的使用
 */
function addScript2Web(webContents, scriptPath) {
    fs.readFile(scriptPath, (err, data) => {
        if (err) {
            console.error(`添加脚本至网页时出现错误:${err}`);
            return;
        }
        // console.log(`脚本：${data}`); 
        webContents.executeJavaScript(`
                var mScript = document.createElement('script');
                mScript.innerHTML = \`${data}\`;
                document.head.appendChild(mScript);`
        ).catch((error) => {       
        });
        // console.log(`
        //     var mScript = document.createElement('script');
        //     mScript.innerHTML = &quot${data}&quot;
        //     document.head.appendChild(mScript);`);
    })


}


module.exports = {
    createDomMonitor_IsExist,
    readFileAsStream,
    readFile,
    addScript2Web
} 